<template>
  <div>
    <el-row class="file-header">
      <el-col style="width:490px">
        <el-button 
        style="width:120px"
        @click="goBack()" 
        type="danger"
        >返回上一页</el-button>
        <el-button
          style="width:100px"
          type="primary"
          icon="el-icon-view"
          @click="previewWeekly(filePath)"
        >预览</el-button>
        <el-button
          style="width:100px"
          type="primary"
          icon="el-icon-download"
          @click=" downloadWeekly(filePath)"
        >下载</el-button>
        <el-button
          style="width:100px"
          type="primary"
          icon="el-icon-refresh-left"
          @click="newWell()"
        >刷新</el-button>
      </el-col>
      <el-col style="width:490px">
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="UrlUp"
          :headers="header"
          :data="{wellName:this.input2}"
          :on-remove="handleRemove"
          :file-list="fileList"
          :auto-upload="false"
          multiple
          :limit="5"
          :on-exceed="handleExceed"
          :on-change="handData"
          :on-success="handleSuccess"
        >
          <el-button slot="trigger" type="primary" >选取文件</el-button>
          <el-button
            style="width:100px"
            type="success"
            @click="submitUpload"
          >上传</el-button>
          <div slot="tip" class="el-upload__tip"></div>
        </el-upload>
      </el-col>
      
      <!-- <el-col :span="3" style="width:150px;margin-right:10px">
        <el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
          手动输入地址
        </el-button>
      </el-col> -->
    </el-row>
    <el-tree
      default-expand-all
      node-key="filePath"
      class="filter-tree"
      style="margin-top:50px"
      :data="data"
      :props="defaultProps"
      :filter-node-method="filterNode"
      ref="tree"
      :check-on-click-node="true"
      highlight-current
      @check-change="handleClick"
      check-strictly
    />
    <div><el-drawer
      title="手动输入文件上传地址，如：LD10-3-1\固井作业"
      :visible.sync="drawer"
      size="30%"
      :before-close="handleClose"
      >
      <span><el-input v-model="input" placeholder="请输入地址" clearable></el-input></span>
    </el-drawer></div>
  </div>
</template>

<script>
    import {
    SERVER_URL
  } from "@/util/constant";
import pdf from 'vue-pdf'
import Vue from 'vue'
import { COOKIE_LIST } from '@/util/constant'
import Cookie from 'js-cookie'
import { downloadPDF, getTree, getPath, upFile } from '@/api/module/well'
import { Upload ,Drawer} from 'element-ui'
export default {
  components: {
    pdf,
    elUpload: Upload,
    elDrawer: Drawer
  },
  data() {
    return {
      UrlUp:'',
      input: '',
      input2:'',
      drawer: false,
      number: '0',
      fileList: [],
      a: '',
      b: [],
      d: [],
      filePath: '',
      rpath: '',
      data: [],
      data1: [],
      src0: '',
      src: '',
      tableData: [],
      form: {
        wellname: '',
        fileName: '',
        wellName: '',
        test: '',
        pager: {},
        defaultProps: {
          children: 'children',
          label: 'name'
        }
      },
      // 文件上传设定token
      header: {
        Authorization: Cookie.get(COOKIE_LIST.AUTHORIZATION)
      }
    }
  },
  created() {
    this.baseData = this.$route.params.data
    this.form = this.$route.params.filterForm
    this.pager = this.$route.params.pager
  },
  mounted() {
    this.getWell()
    this.testURL()
    // this.handleChange1()
  },
  methods: {
    testURL(){
      this.UrlUp=SERVER_URL+"/dataQuery/upload/"
console.log(this.UrlUp)
      },
    //抽屉提示
    handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.input2 = this.input.replace(/\\/g, 'xiegang')
            this.input2 = encodeURIComponent(this.input2)
            console.log(this.input2)
            if(this.input2=='')
            {
              this.input2=this.wellName
            }
            done();
          })
          .catch(_ => {});
      },
    //手动刷新
    newWell(){
      this.getWell()
      alert('大文件上传如未刷新成功，请稍后再试')
    },
    submitUpload() {
      // console.log(Cookie.get(COOKIE_LIST.AUTHORIZATION))
      console.log(this.UrlUp)
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      this.form.fileName = file.name[0]
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handleSuccess(){
      this.newWell()
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },

    handData(file, fileList) {
      console.log(fileList)
      console.log(file)
    },
    test() {
      console.log(this.fileName)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    goBack() {
      this.$router.push({
        name: 'wellQuery',
        params: {
          filterForm: this.form,
          pager: this.pager
        }
      })
    },
    handleClick(data, checked, node) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([data])
        if (typeof data.children === 'undefined') {
          this.getDWell1()
        }
      }
    },
    getDWell1() {
      this.b = this.$refs.tree.getCheckedKeys()
      console.log(this.b)
      var c = this.b[0]
      this.d = c.split('\\')[c.split('\\').length - 1]

      this.b.forEach(item => {
        if (item !== '') {
          this.filePath = item.replace(/\\\\/g, '\\')
          this.filePath = this.filePath.replace(/\\/g, 'xiegang')
          this.filePath = encodeURIComponent(this.filePath)
          this.a = this.filePath
        }
      })
      // this.b.filter(item => item !== "")
      // console.log(this.b.filter(item => item !== ""))
      // let a = this.b.filter(item => item !== "")[0]
      // a = a.replace(/\\\\/g, '\\')
      //      a = a.replace(/\\/g, 'xiegang')
      //      a=encodeURIComponent(a)
      //      this.a = a
    },
    getWell() {
      this.wellName = this.$route.params.data.WELLNAME
      this.input2 = this.wellName
      console.log(this.wellName)
      getTree(this.wellName)
        .then(res => {
          this.data = res.data.data
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    // 预览PDF
    // 预览
    previewWeekly(wellName) {
      // 调用子组件的预览方法
      // 完整的地址应该是发布到服务器的地址，不应该是localhost:8080这样的
      // Vue.prototype.ApiUrl 用来读取服务器地址 比如:
      // http://192.168.8.152:8080/MixShowView-Web/reports/preview/1
      wellName = this.filePath
      var suffix_wellName = wellName.split('.')[wellName.split('.').length - 1]
      if (suffix_wellName == 'pdf'||suffix_wellName == 'png'||suffix_wellName == 'jpg'||suffix_wellName == 'PNG'||suffix_wellName == 'bmp'||suffix_wellName == 'tif'||suffix_wellName == 'JPEG'||suffix_wellName == 'gif') {
        this.previewPDF(
          SERVER_URL + '/dataQuery/preview/' + wellName
        )
      } else {
        alert('该文件格式不支持预览')
      }
    },
    // 封装预览pdf
    previewPDF(url) {
      this.src = pdf.createLoadingTask(url)
      window.open(url)
    },
    // 下载
    downloadWeekly(fileName) {
      this.test = fileName
      downloadPDF(this.test)
        .then(res => {
          // 调用下载方法，把后端传过来的流传给fileDownload方法
          this.fileDownload(res.data, fileName)
          console.log(res)
          console.log(res.config.url)
          this.src0 = res.config.url
        })
        .catch(err => {
          this.$message.error(err.message)
        })
      // 调用下载方法
      // this.$refs.pdf.downloadPDF(Vue.prototype.ApiUrl + '/reports/download/' + fileName)
    },
    // 封装的下载方法
    fileDownload: function(data, fileName) {
      let blob = new Blob([data], {
        // type类型后端返回来的数据中会有，根据自己实际进行修改
        type: 'application/octet-stream'
      })
      let filename = this.d
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        var blobURL = window.URL.createObjectURL(blob)
        // 创建隐藏<a>标签进行下载
        var tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    }
  }
}
</script>
<style scoped>
.el-button{
  width: 150px;
}
.file-header{
  background-color: #fff;
  position: fixed;
  z-index: 98;
  top:50px;
  padding-top: 20px;
}

</style>
